import { Component, OnInit, Inject, ViewChild, AfterViewChecked } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { NgForm, FormControl } from '@angular/forms';
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA, MatDatepickerInputEvent} from '@angular/material';
import { Moment } from 'moment';
import * as moment from 'moment';
declare var $: any;
import { Asset} from '../../models/Asset';
import { SelectionModel } from '@angular/cdk/collections';
import {map, tap} from 'rxjs/operators';
import { environment } from '../../environments/environment';
import { DepartmentService } from '../../service/departmentService';
import { Department } from '../../models/Department';
import { UserService } from '../../service/userService';
import { AssetService } from '../../service/assetService';
import { User } from '../../models/User';
import { DepartmentaddComponent } from '../departmentadd/departmentadd';
import { UseraddComponent } from '../useradd/useradd';
import { Deliver, RepairStatusMap, RepairStatus } from '../../models/Deliver';
import { RepairService } from '../../service/repairService';
import { LoginService } from '../../service/loginService';
import {AssetType} from '../../models/AssetType';
import {IActionMapping, ITreeOptions, TreeComponent} from 'angular-tree-component';
import { Loginauth } from '../../service/loginauth';

@Component({
  templateUrl: './repairadd.html',
  styleUrls: ['./repairadd.css']
})
export class RepairaddComponent implements OnInit, AfterViewChecked {
  options: ITreeOptions = {};
  nodes: any = [];
  assettypeName: string;
  environment = environment;
  typetree: boolean = false;
  @ViewChild(TreeComponent)
  private tree: TreeComponent;
  assetTypes: AssetType[];
  messages = {
    reason: '',
    status: '',
    repairUserid: '',
    departmentid: ''
  };
  RepairStatusMap = RepairStatusMap;
  RepairStatus = RepairStatus;
  selection: SelectionModel<Asset>;
  asset: Asset;
  deliver: Deliver;
  assets: Asset[];
  departments: Department[];
  users: User[];
  departmentid: number;
  appearSearch: boolean = false;
  start_createDate: any;
  end_createDate: any;
  beginCtrl = new FormControl();
  endCtrl = new FormControl();
  actionMapping: IActionMapping = {
    mouse: {
      click: (tree, node, $event) => {
        this.asset.assetType = node.data.GDZCLB_DM;
        this.assettypeName = node.data.GDZCLBMC;
        this.typetree = false;
      }
    }
  };
  page = 1;
  pageSize = 100000;
  total: number;
  assetIds: any = [];
  isAdmin: boolean;
  user: User;
  cols = ['select', 'assetCode', 'assetName', 'assetType', 'assetDate', 'departName', 'username'];
  constructor(
    private departmentService: DepartmentService,
    private userService: UserService,
    private assetService: AssetService,
    private repairService: RepairService,
    private dialog: MatDialog,
    private loginService: LoginService,
    private route: ActivatedRoute,
    private loginauthService: Loginauth,
    private dialogRef: MatDialogRef<RepairaddComponent>,
  ) {
  }
  @ViewChild('repairForm')
  repairForm: NgForm;
  ngAfterViewChecked() {
    if (this.repairForm) {
      this.repairForm.valueChanges.subscribe(data => this.checkValidate());
    }
  }

  ngOnInit() {
    this.loginauthService.checkAdmin().subscribe((isAdmin: boolean) => {
      this.isAdmin = isAdmin;
    })
    this.asset = new Asset();
    this.asset.sysUser = new User();
    this.asset.sysDepartment = new Department();
    this.assetService.getAssetTypes().subscribe((res) => {
      this.assetTypes = res.res;
      for (let i = 0; i < this.assetTypes.length; i++) {
        this.nodes.push({GDZCLBMC: this.assetTypes[i].GDZCLBMC, GDZCLB_DM: this.assetTypes[i].GDZCLB_DM});
      }
      this.nodes.forEach((node, index) => {
        node.children = this.assetTypes[index].children;
      })
    })
    this.options = {displayField: 'GDZCLBMC', idField: 'GDZCLB_DM', actionMapping: this.actionMapping };
    this.deliver = new Deliver();
    this.deliver.sysUser = new User();
    this.deliver.sysUser.realName = this.loginService.user.username;
    this.deliver.repairDateShow = new FormControl(moment(this.deliver.repairDate));
    this.deliver.repairDate = moment(this.deliver.repairDate).toDate();
    const initialSelection = [];
    const allowMultiSelect = true;
    this.selection = new SelectionModel<Asset>(allowMultiSelect, initialSelection);
    this.getDepartments();
    this.getAssets(this.page).subscribe();
  }

  isAllSelected() {
    const numSelected = this.selection.selected.length;
    const numRows = this.assets.length;
    return numSelected === numRows;
  }
  allToggle() {
    this.isAllSelected() ?
      this.selection.clear() :
      this.assets.forEach(row => {this.selection.select(row);});

  }
  itemChanged(item, event) {
    item.isChecked = event.checked;
    if (item.isChecked) {
      this.assetIds.push(item.id);
    } else {
      for (let i = 0; i < this.assetIds.length; i++ ) {
        if (this.assetIds[i] === item.id) {
          this.assetIds.splice(i, 1);
        }
      }
    }
  }
  appearSearchbox() {
    this.appearSearch = true;
  }
  bigsearch() {
    this.appearSearch = false;
    this.getAssets(this.page).subscribe();
  }
  onSwitchDate(_: Moment) {
    this.start_createDate = this.beginCtrl.value;
    this.end_createDate = this.endCtrl.value;
  }
  closesearch() {
    this.appearSearch = false;
  }
  showtypeTree() {
    this.typetree = !this.typetree;
  }
  hidetree() {
    this.typetree = false;
  }
  reset() {
    this.asset = new Asset();
    this.asset.sysUser = new User();
    this.asset.sysDepartment = new Department();
    this.assettypeName = '';
    this.beginCtrl = new FormControl();
    this.endCtrl = new FormControl();
    this.start_createDate = false;
    this.end_createDate = false;
  }
  trackById(index: number, item: any) {
    return item.id;
  }
  onPageChanged(page: number) {
    this.page = page;
    this.getAssets(page).subscribe();
  }
  onSelectrepairDate(event: MatDatepickerInputEvent<Moment>) {
    this.deliver.repairDate = event.value.toDate();
    this.deliver.repairDateShow = new FormControl(event.value);
  }
  getAssets(page) {
    const options: any = {};
    options.repairStatus = 1;
    if (this.asset.assetName) {options.assetName = this.asset.assetName; }
    if (this.asset.assetCode) {options.assetCode = this.asset.assetCode; }
    if (this.asset.assetVersion) {options.assetVersion = this.asset.assetVersion; }
    if (this.asset.sourceComefrom) {options.sourceComefrom = this.asset.sourceComefrom; }
    if (this.asset.assetBrand) {options.assetBrand = this.asset.assetBrand; }
    if (this.asset.sysUser.username) {options.assetName = this.asset.sysUser.username; }
    if (this.asset.position) {options.position = this.asset.position; }
    if (this.asset.snNum) {options.snNum = this.asset.snNum; }
    if (this.asset.invoiceNum) {options.invoiceNum = this.asset.invoiceNum; }
    if (this.asset.remark) {options.remark = this.asset.remark; }
    if (this.asset.assetType) {options.assetType = this.asset.assetType; }
    if (this.asset.source) {options.source = this.asset.source; }
    if (this.asset.sysDepartment.id) {options.assetDepartmentId = this.asset.sysDepartment.id; }
    if (this.asset.sysUser.id) {options.assetUserId = this.asset.sysUser.id; }
    if (this.start_createDate) {const start = this.start_createDate.toDate(); options.start_createDate = start; }
    if (this.end_createDate) {const end = this.end_createDate.toDate(); options.end_createDate = end ; }
    return this.assetService.getAssets(page, this.pageSize, options).pipe(tap((res) => {
      this.assets = res.res;
      this.total = res.total;
      this.page = page;
    }));
  }
  getDepartments() {
    this.departmentService.getAllDepartments().subscribe((res) => {
      this.departments = res.res;

    })
  }

  changeDepartment(departmentId) {
    this.departmentid = departmentId;
    this.getUsers();
  }
  getUsers() {
     this.userService.getUsers(1, 20, this.departmentid).subscribe((res) => {
      this.users = res.res;
    })
  }
  addDepartment() {
    const dialogRef = this.dialog.open(DepartmentaddComponent, {
      width: '500px',
      height: '300px'
    });
    dialogRef.afterClosed().subscribe((result) => {
      this.getDepartments();
    })
  }
  addPerson() {
    const dialogRef = this.dialog.open(UseraddComponent, {
      width: '500px',
      height: '500px',
      data: {
        departments: this.departments
      }
    });
    dialogRef.afterClosed().subscribe((result) => {
      this.getUsers();
    })
  }

  onSubmit() {
    this.deliver.assetids = this.assetIds.join(',');
    this.deliver.userid = Number(this.loginService.user.id);
    this.checkValidate(true);
    if (this.repairForm.invalid) {
      // 触发mat的error
      this.repairForm.onSubmit(null);
      return false;
    }
    this.repairService.create(this.deliver).subscribe((res) => {
      if (res.success) {
        this.dialogRef.close(res.res);
      }
    })

  }
  checkValidate(isSubmit?: boolean) {
    const form = this.repairForm;

    for (const field in RepairaddComponent.ErrorMessages) {

      const control = form.controls[field];

      if (control && control.valid) {
        this.messages[field] = '';
      }
      if (control && (control.dirty || isSubmit) && !control.valid) {
        const messages = RepairaddComponent.ErrorMessages[field];
        if (control.errors) {
          this.messages[field] = messages[Object.keys(control.errors)[0]];
        }
      }
    }
  }

  static ErrorMessages = {
    reason: {
      required: '报修原因不能为空'
    },
    status: {
      required: '维修状态不能为空'
    },
    repairUserid: {
      required: '报修人不能为空'
    },
    departmentid: {
      required: '报修部门不能为空'
    }
  };
}
